import { message } from "antd";
import { cloneDeep, merge } from "lodash";
import { hashHistory } from "dva/router";
import {
  queryAllAddress,
  getDetail,
  AllEstateList,
  allActivityList,
  submit,
  advertisementAudit,
} from "./advertisingWindowDetailServ.js";
import { makeAddress } from "utils/util";
import moment from "moment";
const delay = (ms) =>
  new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
const defultState = {
  //推荐楼盘
  query: {
    provinceCodes: [],
    cityCodes: [],
    wholeCountry: false,
    imgUrl: [],
  },
  clique: "",
  city: [],
  actionType: "",
  areaList1: [],
  projectList: [],
  visible: false,
  value: 1,
  local: false,
  num: "",
  channelIndex: 1,
  biz: {
    1: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    2: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    3: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    4: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    5: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    6: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    7: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    9: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    10: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    11: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    12: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    13: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
    14: {
      queryForm: {},
      rowSelection_type: "radio",
      selectedRowKeys: [],
    },
  },
  biz2: {
    queryForm: {},
    rowSelection_type: "radio",
  },
  hrefModalObj: {
    visible: false,
    hrefType: "",
  },
  currentItem: [],
  clique: "",
  btnLoading: false,
  confirmAudit: false,
  ignoreReason: false,
  auditDesc: "", //驳回原因
  // 加载中状态
  loadingGroup:{
    '0': false,
    '-1': false,
    '1': false,
    '2': false,
  }
};

const tmpModule = {
  state: cloneDeep(defultState),
  subscriptions: {
    setup({ dispatch, history }) {
      let clique = localStorage.getItem("clique");
      history.listen(({ pathname, query }) => {
        if ("" + tmpModule.pathname === "" + pathname) {
          dispatch({ type: "updateStore", payload: cloneDeep(defultState) });
          dispatch({
            type: "updateStore",
            payload: {
              actionType: query.actionType,
              advertisementId: query.advertisementId,
              clique: localStorage.getItem("clique"),
            },
          });
          dispatch({ type: "getAreaList", payload: {} });
          dispatch({ type: "getAllEstateList" });
        }
      });
    },
  },

  effects: {
    //获取省市
    *getAreaList({ payload }, { put, call, select }) {
      let { actionType, advertisementId, clique } = yield select(
        (state) => state[tmpModule.namespace]
      );
      const { data, success } = yield call(queryAllAddress);
      if (success) {
        let arr = [];
        data.map((item, index) => {
          arr.push(item.value);
        });
        let areaList1 = [];
        if (JSON.parse(clique)) {
          let arr = [data[0]];
          let attr = [data[data.length - 1]];
          data[0] = {
            label: "北京",
            value: "110100",
            children: arr,
          };
          data[data.length - 1] = {
            label: "澳门",
            value: "820000",
            children: attr,
          };
        }
        // //去掉第三级，
        // areaList = makeAddress(data,2)
        areaList1 = makeAddress(data, 2);
        areaList1 = data;
        areaList1.shift();
        yield put({
          type: "updateStore",
          payload: { areaList1, roleArea: arr },
        });
        if (actionType == "detail" || actionType == "edit") {
          yield put({ type: "getDetail", payload: { advertisementId } });
        }
      }
    },
    //获取活动详细信息
    *getDetail({ payload }, { put, call, select }) {
      const { data, success } = yield call(getDetail, payload);

      if (success) {
        //回来的数据回显
        // debugger
        let { city, areaList1, currentItem, roleArea } = yield select(
          (state) => state[tmpModule.namespace]
        );
        for (var i = 0; i < data.provinceCodes.length; i++) {
          // console.log(query.provinceCodes[i])
          if (roleArea.indexOf(data.provinceCodes[i]) == -1) {
            delete data.provinceCodes[i];
          }
          for (var y = 0; y < areaList1.length; y++) {
            // console.log(areaList1[y])
            if (data.provinceCodes[i] == areaList1[y].value) {
              city[i] = areaList1[y].children;
              // console.log(areaList1[y])
            }
          }
        }
        console.log(data, "----");
        let hrefModalObj = {};
        hrefModalObj.linkUrl = data.linkUrl;
        hrefModalObj.hrefType = data.linkType;
        hrefModalObj.btnName = data.btnName;
        if (data.wholeCountry) {
          data.provinceCodes = ["0"];
        }
        //(1:推介 2：内部链接 3：资讯 4:外部链接 5：活动，6：预约看房，7：美房详情)
        if (["1", "6", "7"].indexOf(data.linkType + "") > -1) {
          currentItem = [data.productId];
        } else if (["5", "3"].indexOf(data.linkType + "") > -1) {
          currentItem = [data.contentId];
        } else if (["2"].indexOf(data.linkType + "") > -1) {
          currentItem = [data.linkUrl.split("=")[1]];
        }
        hrefModalObj.params = {
          contentId: data.contentId,
          productId: data.productId,
          btnName: data.btnName,
        };
        console.log(hrefModalObj);
        // console.log(city)
        yield put({
          type: "getActivityList",
          payload: { businessId: data.productId },
        });
        yield put({
          type: "updateStore",
          payload: { city, query: data, hrefModalObj, currentItem },
        });
      }
    },

    //提交表单
    *submit({ payload }, { put, call, select }) {
      try {
        if(JSON.stringify(payload) == '{}'){
          yield put({ type: 'updateStore', payload: { btnLoading: true } })
        }
        let { query, hrefModalObj, actionType } = yield select(
          (state) => state[tmpModule.namespace]
        );
        let objParmas = {};
        if (query.imgUrl.length == 0) {
          message.error("请上传首页活动图");
          return false;
        } else if (
          new Date(query.endDate).getTime() -
            new Date(query.startDate).getTime() >
          15 * 24 * 3600 * 1000
        ) {
          message.error("设置生效日期的范围最长不能超过15天");
          return false;
        } else {
          let params = hrefModalObj.params;
          // console.log(params)
          // console.log(query)
          query.linkType = hrefModalObj.hrefType;
          objParmas = {
            ...cloneDeep(query),
            ...cloneDeep(hrefModalObj),
            ...params,
          };
          if (query.productId) {
            objParmas.productId = query.productId;
          }
          if (objParmas.seckillActivityId) {
            objParmas.contentId = objParmas.seckillActivityId;
          }
          if (objParmas.wholeCountry || objParmas.location == "2") {
            delete objParmas.provinceCodes;
            delete objParmas.cityCodes;
          }
          const { success ,msg} = yield call(submit, { ...objParmas, type: 1 });
          if (success) {
            // if (moment(query.startDate).isAfter(moment().add(10, "minutes"))) {
            //   message.success(
            //     `您设置的弹窗广告将在${query.startDate}后10分钟内生效，请关注`
            //   );
            // } else {
            //   message.success(`您设置的弹窗广告将在10分钟之内生效，请稍候`);
            // }
            if (JSON.stringify(payload) != '{}' && payload.AuditOk) {
              let advertisementId = msg
              yield put({ type: 'advertisementAuditsubmit', payload: { advertisementId, auditStatus: 1 } })
            } else {
              message.success(actionType == 'add' ? '新增成功' : '编辑成功')
              hashHistory.push("/home/advertisementAdmin/advertisingWindowList?closeTab=true");
            }
            //message.success(actionType=='add'?'新增成功':'编辑成功')
            
          }
          yield call(delay, 2000);
          yield put({ type: "updateStore", payload: { btnLoading: false } });
        }
      } catch (e) {
        console.log(e);
      }
    },
    //获取所有上架楼盘列表
    *getAllEstateList({ payload }, { put, call, select }) {
      let { projectList } = yield select((state) => state[tmpModule.namespace]);
      const { rows, success, total, pageNo } = yield call(AllEstateList, {
        shelfStatus: "1",
        pageSize: 100000,
      });
      if (success) {
        yield put({
          type: "updateStore",
          payload: {
            projectList: rows,
            projectListTotal: total,
            projectListPageNo: pageNo,
          },
        });
      }
    },
    //获取当前楼盘的活动或资讯列表
    *getActivityList({ payload }, { put, call, select }) {
      console.log(payload);
      const { rows, success, total, pageNo } = yield call(allActivityList, {
        ...payload,
        pageSize: 10000,
        status: 1,
      });
      if (success) {
        console.log(rows);
        yield put({ type: "updateStore", payload: { activityList: rows } });
      }
    },
    // 审核
    *advertisementAuditsubmit({ payload }, { put, call, select }) {
      try {
        let {loadingGroup} = yield select((state) => state[tmpModule.namespace])
        loadingGroup[''+payload.auditStatus+''] = true
        yield put({ type: 'updateStore', payload: { loadingGroup: loadingGroup } })
        const { success } = yield call(advertisementAudit, payload);
        if (success) {
            message.success("操作成功");
            hashHistory.push("/home/advertisementAdmin/advertisingWindowList?closeTab=true");
            
          // put({type: 'getDetail', payload: {advertisementId}})
        }
        loadingGroup[''+payload.auditStatus+''] = false
            yield put({ type: 'updateStore', payload: { loadingGroup: loadingGroup } })
      } catch (error) {
        console.log(error);
      }
    },
  },
  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload);
    },
  },
};
export default tmpModule;
